package com.xiaobias.distributed.pan.seurity.service;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xiaobias.distributed.pan.db.entity.BaiduUser;
import com.xiaobias.distributed.pan.db.service.BaiduUserService;

import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.web.client.RestTemplate;


public class BaiduAuth2UserService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> {
    private final BaiduUserService baiduUserService;
    private RestTemplate restTemplate;

    public BaiduAuth2UserService(BaiduUserService baiduUserService) {
        this.baiduUserService = baiduUserService;
    }

    private RestTemplate getRestTemplate() {
        if (this.restTemplate == null) {
            this.restTemplate = new RestTemplate();
        }

        return this.restTemplate;
    }

    public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
        String accessToken = userRequest.getAccessToken().getTokenValue();
        String openIdUrl = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri() + "?method=uinfo&access_token=" + accessToken;
        com.xiaobias.distributed.pan.seurity.entity.BaiduUser user = this.getRestTemplate().getForObject(openIdUrl, com.xiaobias.distributed.pan.seurity.entity.BaiduUser.class);
        BaiduUser baiduUser = new BaiduUser();
        String uk = user.getUk();
        if (StringUtils.isNotEmpty(uk)) {
            baiduUser.setId(Long.parseLong(uk));
        }

        baiduUser.setBaiduName(user.getBaiduName());
        baiduUser.setNetDiskName(user.getNetdiskName());
        baiduUser.setAvatarUrl(user.getAvatarUrl());
        baiduUser.setToken(accessToken);
        baiduUser.setVipType(user.getVipType());
        baiduUser.setCreateUser(user.getBaiduName());
        baiduUser.setUpdateUser(user.getBaiduName());
        baiduUser.setUk(user.getUk());
        this.baiduUserService.saveOrUpdate(baiduUser);
        return user;
    }
}
